package projetjee

import org.springframework.dao.DataIntegrityViolationException
import grails.plugins.springsecurity.Secured
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

class UserController {

	/*utile pour recuperer les info de connexions*/
	def springSecurityService

	static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def vote(){
	}

	def index() {
		redirect(action: "list", params: params)
	}

	def list() {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[userInstanceList: User.list(params), userInstanceTotal: User.count()]
	}

	def create() {
		[userInstance: new User(params)]
	}

	def save() {
		def userInstance = new User(params)
		if (!userInstance.save(flush: true)) {
			render(view: "create", model: [userInstance: userInstance])
			return
		}
		/*on donne le role de user lors de l'enregistrement'*/
		UserRole.create userInstance, Role.findByAuthority('ROLE_USER'), true
		flash.message = message(code: 'default.created.message', args: [
			message(code: 'user.label', default: 'User'),
			userInstance.id
		])
		redirect(action: "show", id: userInstance.id)
	}
	
	/*seul les admin et les user peuvent y acceder*/
	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def voir(){
		def userInstance = springSecurityService.getCurrentUser().getId()
		redirect(controller: 'user', action: 'show', id: userInstance)
	}

	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def show() {
		def userInstance = User.get(params.id)
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'user.label', default: 'User'),
				params.id
			])
			redirect(action: "list")
			return
		}

		[userInstance: userInstance]
	}
	
	/*pour voter*/
	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def voter() {
		
		/*on recupere l'id et on le converti en string*/
		def userIdString1 = params.id
		def userId1 = Integer.parseInt(userIdString1)
		/*l'user pour qui le vote va compter*/
		def user1 = User.get(userId1)

		/*algorithme de vote*/
		def scoreTotal1 = user1.getScoreTotal()
		def nbVotant1 = user1.getNbVotant()
		def nbVotantPositif1 = user1.getNbVotantPositif()
		def vote1 = user1.getVote()
		scoreTotal1+= 20
		nbVotant1++
		nbVotantPositif1++
		vote1 = (scoreTotal1/nbVotant1)
		//println "Gagnant 1 : "+ user1.getNom()+" --ScoreTotal :"+scoreTotal1+" --NbVotant1 :"+nbVotant1+" --Vote : "+vote1
		vote1 = vote1.toInteger()
		//println "Gagnant 2 : "+ user1.getNom()+" --ScoreTotal :"+scoreTotal1+" --NbVotant1 :"+nbVotant1+" --Vote : "+vote1
		user1.setScoreTotal(scoreTotal1)
		user1.setNbVotant(nbVotant1)
		user1.setNbVotantPositif(nbVotantPositif1)
		user1.setVote(vote1)

		/*l'user pour qui on a pas vote*/
		def userIdString2 = params['ids']
		def userId2 = Integer.parseInt(userIdString2);
		def user2 = User.get(userId2)

		def scoreTotal2 = user2.getScoreTotal()
		def nbVotant2 = user2.getNbVotant()
		def vote2 = user2.getVote()
		scoreTotal2+= 10
		nbVotant2++
		vote2 = (scoreTotal2/nbVotant2)
		//println "Perdant 1 : "+ user2.getNom()+" --ScoreTotal :"+scoreTotal2+" --NbVotant1 :"+nbVotant2+" --Vote : "+vote2
		vote2 = vote2.toInteger()
		//println "Perdant 2 : "+ user2.getNom()+" --ScoreTotal :"+scoreTotal2+" --NbVotant1 :"+nbVotant2+" --Vote : "+vote2
		user2.setScoreTotal(scoreTotal2)
		user2.setNbVotant(nbVotant2)
		user2.setVote(vote2)

		/*redirection vers la liste des users*/
		redirect(controller: 'user', action: 'list')

	}

	/*rediriger vers le profil d'un membre a partir de son id depuis vote.gsp*/
	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def showVote() {
		def p = params.id
		def i = Integer.parseInt(p);
		def userI = User.get(i)
		def userInstance = userI.getId()
		redirect(controller: 'user', action: 'show', id: userInstance)
	}
	/*rediriger vers la photo d'un membre a partir de son id depuis vote.gsp*/
	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def showImage() {
		def p = params.id
		def i = Integer.parseInt(p);
		def userI = User.get(i)
		def userInstance = userI.getId()
		redirect(controller: 'user', action: 'viewImage', id: userInstance)
	}

	/*pour afficher l'image*/
	@Secured(['ROLE_ADMIN','ROLE_USER'])
	def viewImage =  {
		def photoTemp = User.get( params.id)
		byte[] image = photoTemp.photoProfil
		response.contentType = "image/jpeg"
		response.outputStream << image
	}

	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def edit() {
		def userInstance = User.get(params.id)
		/*si ce n'est pas son propre profil, on ne peut l'editer
		 * on comprare l'id de l'utilisateur actuel celui du profil que l'on veut modifier*/
		if(userInstance==springSecurityService.getCurrentUser()){
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'user.label', default: 'User'),
				params.id
			])
			redirect(action: "list")
			return
		}

		[userInstance: userInstance]
		}else redirect (action : "list")
	}

	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def update() {
		def userInstance = User.get(params.id)
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'user.label', default: 'User'),
				params.id
			])
			redirect(action: "list")
			return
		}

		if (params.version) {
			def version = params.version.toLong()
			if (userInstance.version > version) {
				userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
						[
							message(code: 'user.label', default: 'User')]
						as Object[],
						"Another user has updated this User while you were editing")
				render(view: "edit", model: [userInstance: userInstance])
				return
			}
		}

		userInstance.properties = params

		if (!userInstance.save(flush: true)) {
			render(view: "edit", model: [userInstance: userInstance])
			return
		}

		flash.message = message(code: 'default.updated.message', args: [
			message(code: 'user.label', default: 'User'),
			userInstance.id
		])
		redirect(action: "show", id: userInstance.id)
	}

	@Secured(['ROLE_ADMIN', 'ROLE_USER'])
	def delete() {
		def userInstance = User.get(params.id)
		/*si ce n'est pas son propre profil, on ne peut le supprimer
		* on comprare l'id de l'utilisateur actuel a celui du profil que l'on veut modifier*/
		if(userInstance==springSecurityService.getCurrentUser()){
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'user.label', default: 'User'),
				params.id
			])
			redirect(action: "list")
			return
		}
		
			try {
				userInstance.delete(flush: true)
				flash.message = message(code: 'default.deleted.message', args: [
					message(code: 'user.label', default: 'User'),
					params.id
				])
				redirect(action: "list")
			}
			catch (DataIntegrityViolationException e) {
				flash.message = message(code: 'default.not.deleted.message', args: [
					message(code: 'user.label', default: 'User'),
					params.id
				])
				redirect(action: "show", id: params.id)
			}
		}else redirect(action: "list")
	}
}
